// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// u [author] rhyme_lph
// K [email]  rhymelph@gmail.com
// A [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/provider/setting/preference/number_format_provider.dart';
import 'package:finance_app/src/provider/setting/preferences_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/page/setting/preference/number_format_info_page.dart';

class NumberFormatInfoProvider extends BaseProvider {
  TextEditingController prefixController = TextEditingController();
  FocusNode prefixFocusNode = FocusNode();

  TextEditingController digitsController = TextEditingController();
  FocusNode digitsFocusNode = FocusNode();

  String get preview => '${prefixController.text}${digitsController.text}';

  @override
  Future get dataFuture => null;

  @override
  void dispose() {
    super.dispose();
    prefixController.dispose();
    prefixFocusNode.dispose();
    digitsController.dispose();
    digitsFocusNode.dispose();
  }

  @override
  void initState() {
    super.initState();
    prefixController.addListener(_handleUpdate);
    digitsController.addListener(_handleUpdate);
  }

  void initValue(String value) {
    prefixController.text = value.substring(0, value.indexOf('0'));
    digitsController.text = value.substring(value.indexOf('0'));
  }

  void _handleUpdate() {
    update();
    updateNumberFormatPreference();
  }

  void updateNumberFormatPreference() {
    final pref = Providers.get<NumberFormatProvider>(
        RouterGenProviders.numberFormatPage, null);
    if (pref != null) {
      pref.updateFromInput(preview);
    }
  }
}
